package com.by.controller;

import cn.hutool.core.bean.BeanUtil;
import com.by.bean.LoginBean;
import com.by.bean.User;

import com.by.common.bean.ResultBean;
import com.by.common.controller.BaseController;
import com.by.common.group.ISave;
import com.by.common.group.V;
import com.by.service.UserService;
import com.by.token.TokenTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "用户管理")
@RequestMapping("/api")
public class UserControllerFinally extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    TokenTemplate tokenTemplate;

    @ApiOperation("用户注册")
    @PostMapping("/user/save")
    public ResultBean save(@Validated(ISave.class) @RequestBody User user, BindingResult result) {
        V.validate(result);
        int rs = userService.add(user);
        return saveResult(rs);
    }
    @ApiImplicitParam(name = "account", value = "账号", required = true, dataTypeClass = String.class, paramType = "query")
    @ApiOperation("检查账号是否存在")
    @GetMapping("/user/check")
    public ResultBean check(@RequestParam(required = true) String account) {
        int rs = userService.checkUser(account);
        String tmp = rs == 0 ? "no" : "yes";
        return success("检查账号是否存在", tmp);
    }


    @ApiOperation("登录")
    @PostMapping("/user/login")
    public ResultBean login(@Validated @RequestBody LoginBean loginBean, BindingResult result) {
        V.validate(result);
        //根据用户名查询
        User user = userService.queryByAccount(loginBean.getAccount());
        if (null == user) {
            return fail("账号不存在！");
        }

        //判断密码是否正确
        //加密用户输入的密码
        String pwd = DigestUtils.md5DigestAsHex(loginBean.getPassword().getBytes());
        if (!pwd.equals(user.getPassword())) return fail("账号或密码错误！");

        //判断账号状态
        if (user.getIsdel() == 1) return fail("该账号已禁用，请联系管理员！");
        //将用户信息转换为map
        Map map = BeanUtil.beanToMap(user);
        //将密码移除
        map.remove("password");

        //生成token
        String token = tokenTemplate.generateToken(map);
        map.put("accessToken", token);
        return success("登录成功", map);
    }
}
